package com.example.demo.service;
import com.alibaba.fastjson.JSON;
import com.example.demo.chat.ChatEndpoint;
import com.example.demo.entity.*;
import com.example.demo.mapper.UserMapper;
import com.example.demo.util.Utils;
import jakarta.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserService {
    private static String resource = new ApplicationHome().getDir().getAbsolutePath()+"\\src\\main\\resources\\";
    private static String goodsSrc = resource+"goods\\";
    private static String iconSrc = resource+"icons\\";
    private static String sharesSrc = resource+"shares"+"\\";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ChatEndpoint chatEndpoint;

    public List<User_Test2> findAll(){
        return userMapper.findAll();
    }
    public boolean exist(String admin){
        return userMapper.exist(admin);
    }
    public boolean login(String admin,String pswd){
        String passwd = userMapper.getPassword(admin);
        if(passwd==null){
            return false;
        }
        if(Utils.verifyPassword(pswd,passwd)){
            System.out.println("密码正确");
        }else {
            System.out.println("密码错误");
        }
        return Utils.verifyPassword(pswd,passwd);

    }
    public User_Test2 getUserByName(String name){
        return userMapper.getUserByName(name);
    }
    public String modify_password(String account,String password){
        System.out.println(account);
        System.out.println(password);
        System.out.println(userMapper.modify_password(account,password));
        return userMapper.modify_password(account,password);
    }
    public String getId(String account){
        return userMapper.getId(account);
    }
    public boolean register(String nickName,String account,String password,int customer,int business){
        String encryptedPassword = Utils.hashPassword(password);
        return userMapper.register(nickName,account,encryptedPassword,customer,business);
    }
    public boolean registerNoNickName(String account,String password,int customer,int business){
        List<User_Test2> userTest2s = userMapper.findAll();
        boolean loop = true;
        String randName = "";
        while (loop){
            boolean repeat = false;
            randName = Utils.generateRandomString(8);
            for (User_Test2 user: userTest2s){
                if(randName.equals(user.getNickName())){
                    //出现了重复
                    repeat = true;
                    break;
                }
            }
            loop = repeat;
        }
        String encryptedPassword = Utils.hashPassword(password);
        return userMapper.register(randName,account,encryptedPassword,customer,business);
    }
    public String getNickNameByAccount(String account){
        return userMapper.getNickNameByAccount(account);
    }
    public boolean isCustomer(String account){
        boolean isTrue = false;
        System.out.println(userMapper.getCustomerByAccount(account));
        if(!"0".equals(userMapper.getCustomerByAccount(account))){
            //此时账号已是用户，不可以再注册账号
            isTrue = true;
        }
        return isTrue;
    }
    public boolean isBusiness(String account){
        boolean isTrue = false;
        if(!"0".equals(userMapper.getBusinessByAccount(account))){
            //此账号是商家账号
            isTrue = true;
        }
        return isTrue;
    }
    public boolean businessCreateCustomer(String account){
        return userMapper.businessCreateCustomer(account);
    }
    public boolean addNewGoods(GoodsDetail goodsDetail){
        return userMapper.addNewGoods(goodsDetail);
    }
    public boolean addNewAddress(Address address){return  userMapper.addNewAddress(address);}
    public GoodsDetail[] getAllGoodsDetails(){return userMapper.getAllGoodsDetail();}
    public GoodsDetail[] getGoodsDetailLikeStr(String like){return userMapper.getGoodsDetailsLikeSomeThing(like);}
    public int addLabel(Label label){return userMapper.addLabel(label);}
    public Label[] getLabelsByGoodsId(int goodsId){return userMapper.getLabelsByGoodsId(goodsId);}
    public String getUserId(String admin,String password){return userMapper.getUserId(admin,password);}
    public boolean uploadSharePics(MultipartFile[] files,String shareId){
        return Utils.uploadFiles(files,sharesSrc+shareId);
    }
    public boolean uploadGoodsPics(MultipartFile[] files,String goodsId){
        return Utils.uploadFiles(files,goodsSrc+goodsId);
    }
    public ResponseEntity<Resource> getImgFromSrc(String filePath,boolean isGoods){
        File file = new File(filePath);
        System.out.println(file.getName());
        if (!file.exists()){
            if(isGoods){
                file = new File(goodsSrc+"loadingFail.png");
            }
            //如果这张图片不存在，发送加载失败图像
        }
        return Utils.showImg(file);
    }
    public int getGoodsId(long timestamp,String businessId){
        return userMapper.getGoodsId(timestamp,businessId);
    }
    public int getShareId(long timestamp,String account){
        return userMapper.getShareId(timestamp,account);
    }
    public boolean addNewShare(Share share){return userMapper.addNewShare(share);}
    public Share[] getAllShare(){return  userMapper.getAllShare();}
    public String getAccountByGoodsId(String goodsId){return userMapper.getAccountByGoodsId(goodsId);}
    public GoodsDetail[] getDetailsByBusinessId(String businessId){return userMapper.getDetailsByBusinessId(businessId);}
    public String getShopNameByBusinessId(String BusinessId){
        System.out.println("getShopName:"+BusinessId);
        return userMapper.getShopNameByBusinessId(BusinessId);
    }



    public int addOrder(Order order){return userMapper.addOrder(order);}
//    public int updateOrderState(Order order){return userMapper.updateOrderState(order);}
    public Order[] getOrdersByAccount(String account){return userMapper.getOrdersByUserId(account);}
    public Order[] getOrdersByBusinessId(String businessId){
        int[] goodsIds = userMapper.getGoodsIdsByBusinessId(businessId);
        List<Order> orders = new ArrayList<Order>();
        for(int id:goodsIds){
            System.out.println(id);
            //这里有问题:如果该商品没有对应的订单，意味着加入了一个null
            //并且，这查询结果是一个数组
            Order[] o = userMapper.getOrdersByGoodsId(id);
            if(o.length>0){
                for (int i = 0; i < o.length; i++) {
                    orders.add(o[i]);
                }
            }
        }
        return orders.toArray(new Order[0]);
    }
    public String getGoodsNameByGoodsId(String goodsId){return userMapper.getGoodsNameByGoodsId(goodsId);}
    public int setShopNameByAccount(String shopName,String account){return userMapper.setShopNameByAccount(shopName,account);}
    public boolean updateGoodsDetail(GoodsDetail detail){return userMapper.updateGoodsDetail(detail);}
    public GoodsDetail getDetailById(String goodsId){return userMapper.getDetailById(goodsId);}
    public GoodsDetail[] getDetailsByClassAngGroup(int goodsClass,int goodsGroup){return userMapper.getDetailsByClassAndGroup(goodsClass,goodsGroup);}
    public boolean submitOrder(Order[] orders){
        boolean success = true;
        for (int i = 0; i < orders.length; i++) {
            //用户提交的订单，这里要做的是，将其保存到数据库，并使用websocket对其进行转发
            this.addOrder(orders[i]);

            System.out.println("goodsId:"+orders[i].getGoodsId());
            String account = this.getAccountByGoodsId(""+orders[i].getGoodsId());
            if(this.chatEndpoint.isExist(account)){
                Session session = this.chatEndpoint.getSessionById(account);
                try{
                    session.getBasicRemote().sendText(JSON.toJSONString(new Message("",account,"您有一个新的订单",1)));
                }catch (IOException E){
                    E.printStackTrace();
                    success = false;
                }
            }
        }
        return success;
    }
    public boolean updateOrderState(Order order){
        //通知用户订单状态发生改变
        //直接传递order对象
        if(this.chatEndpoint.isExist(order.getUserId())){
            //发送一个wsMessage对象
            Message message = new Message("",order.getUserId(),"订单状态发生变化",Math.round(System.currentTimeMillis()/1000));
            message.setType(2);
            try{
                this.chatEndpoint.getSessionById(order.getUserId()).getBasicRemote().sendText(JSON.toJSONString(message));

            }catch (IOException E){
                E.printStackTrace();
            }
        }
        return userMapper.updateOrderState(order);
    }
    public Address[] getAddressByAccount(String account){return userMapper.getAddressByAccount(account);}
    public boolean modifyMain(int id,String account){
        if(userMapper.modifyMainAddress(account)){
            return userMapper.addMain(id);
        }
        return false;
    }
    public boolean addAddress(Address address){return userMapper.addAddress(address);}

}
